package com.beiding.workordersystem.system.controller;

import com.beiding.workordersystem.common.standard.R;
import com.beiding.workordersystem.system.entity.RoleEntity;
import com.beiding.workordersystem.system.vo.RoleAssociateAccountVo;
import com.beiding.workordersystem.system.vo.RoleAssociateAuthorityVo;
import com.beiding.workordersystem.system.vo.RoleVo;
import com.beiding.workordersystem.system.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /*
    角色标识或者名称是全局唯一的且非空
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('role_save')")
    R save(@RequestBody @Validated RoleVo roleVo) {
        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(roleVo, roleEntity);
        roleService.save(roleEntity);
        return R.ok(roleEntity.getId());
    }

    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('role_get')")
    R page(@RequestParam String id) {
        return R.ok(roleService.getAndFillChildren(id));
    }

    @GetMapping("/details")
    @PreAuthorize("hasAuthority('role_get')")
    R details(@RequestParam String id) {
        return R.ok(roleService.getDetails(id));
    }

    //为角色分配权限
    @PostMapping("/associateAuthority")
    @PreAuthorize("hasAuthority('role_authority_associate')")
    R associateAuthority(@RequestBody @Validated RoleAssociateAuthorityVo roleAssociateAuthorityVo) {
        roleService.associateAuthority(roleAssociateAuthorityVo.getRoleId(), new HashSet<>(roleAssociateAuthorityVo.getAuthorityIds()));
        return R.ok();
    }

    //角色
    @GetMapping("/delete")
    @PreAuthorize("hasAuthority('role_delete')")
    R delete(@RequestParam String id) {
        roleService.delete(id);
        return R.ok();
    }


    //为角色关联用户
    @PostMapping("/associateAccount")
    @PreAuthorize("hasAuthority('role_user_associate')")
    R associateUser(@RequestBody @Validated RoleAssociateAccountVo roleAssociateUserVo) {
        roleService.associateAccount(roleAssociateUserVo.getRoleId(), new HashSet<>(roleAssociateUserVo.getAccountIds()));
        return R.ok();
    }


}
